package com.wyj.controller;

import com.wf.captcha.utils.CaptchaUtil;
import com.wyj.pojo.User;
import com.wyj.service.UserService;
import com.wyj.service.imp.UserServiceImp;
import com.wyj.util.CommunityConstant;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.jws.WebParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {

    @Autowired
    UserServiceImp userServiceImp;

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String getRegis() {
        return "/site/register";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLogin() {
        return "/site/login";
    }



    //当我们第二次访问这个页面的时候,已经将在model中有这个user 所以可以直接访问
    @RequestMapping(value = "/getDiscussPost", method = RequestMethod.POST)
    public String register(Model model, User user) {

//        new Thread(()->{
        Map<String, Object> map = userServiceImp.register(user);
//        });


        model.addAttribute("user", user);

        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送一封邮件 请尽快激活");
            //这是跳转到主页面。
            model.addAttribute("target", "/index");


            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));

            //返回注册页面显示错误信息
            return "/site/register";
        }
    }

    // http://localhost:8080/community/activation/101/code
    @RequestMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int activation = userServiceImp.activation(userId, code);

//        System.outprintln("++++++++++++" + userId + "++++++++++++");



        if (activation == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "注册成功,");
            //这是跳转到主页面。
            model.addAttribute("target", "/login");
        } else if (activation == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效激活 该账号已经激活成功了");
            //这是跳转到主页面。
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败 您提供的激活码不正确");
            //这是跳转到主页面。
            model.addAttribute("target", "/index");
        }

        return "/site/operate-result";
    }


    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);

    }


    @RequestMapping(value = "/loginIndex", method = RequestMethod.GET)
    public String loginController(String username,
                                  String password,
                                  String code,
                                  boolean remember,
                                  Model model,
                                  HttpServletResponse response,
                                  HttpServletRequest request,
                                  RedirectAttributes rettr
    ) {
        //验证验证码 是否正确  是否为空
        if (StringUtils.isBlank(code) || !CaptchaUtil.ver(code, request)) {
            CaptchaUtil.clear(request);//清空Session
            model.addAttribute("codeMsg", "验证码不正确");
        }

        //如果勾选上记住的话  那么的话这个是失效时间是100天  未勾选的的话 即使12个小时
        int expiredSeconds = remember ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;

        Map<String, Object> map = userServiceImp.login(username, password, expiredSeconds);

        //如果map中的 包含这个 ticket 的话  那么我们就可以存 cookie。
        //走这个if 证明的是 用户名和密码都正确 无误，然后map当中存了个凭证，这样就可以重定向到 index页面  也可以留下个凭证。
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());

            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);

            rettr.addAttribute("username",username);

            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));

            return "/site/login";
        }
    }

    @RequestMapping(value = "/loginOut",method = RequestMethod.GET)
    public String loginOut(@CookieValue("ticket") String ticket) {

        userServiceImp.updateLoginTicket(ticket);

        //将认证结果清除
        SecurityContextHolder.clearContext();

        return "redirect:/login";
    }


    @RequestMapping(path = "/text")
    public String getText(Model model) {
//        model.addAttribute("name","wyj");

        List<User> list = new ArrayList<>();
        list.add(new User(1, "wyj1"));
        list.add(new User(2, "wyj2"));
        list.add(new User(3, "wyj3"));

        model.addAttribute("users", list);


        return "/site/text01";
    }

}
